<template>
  <div id="Training" class="app-container">
    <el-tabs v-if='!homeTab' v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="TimeTable" name="TimeTable" />
      <el-tab-pane v-if='courseAdmin' label="Course" name="Course" />
    </el-tabs>

    <div class="container-fluid">
      <div class="filter-container">

        <el-row type="flex" align="bottom" style="flex-flow:wrap">
          <el-col
            :md="{span:16}"
            :xs="{span:24}"
          >
            <el-date-picker
              v-show="activeName === 'TimeTable'"
              ref="inputRef"
              v-model="uppderDate"
              type="date"
              class="filter-item"
              popper-class="fix-popper"
              clearable
              value-format="yyyy-MM-dd"
              picker-options="pickerOptions"
              :append-to-body="false"
              prefix-icon="falseI"
            />

            <el-input
              v-show="activeName==='Course'"
              v-model="listQuery.keyword"
              placeholder="Keyword"
              clearable
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="handleFilter"
            />

            <el-button v-show="activeName === 'Course'" class="filter-item" type="success" icon="el-icon-search" @click="handleFilter">
              Search
            </el-button>

            <el-select
            v-if="activeName === 'Course'"
              v-model="listQuery.sport"
              :placeholder="'Sport'"
              class="filter-item"
			        clearable

              @change="(l)=>sort_method(0,l)"
            >
            <el-option
              v-for="item in sportList"
              :key="item.sport"
              :label="item.sportName"
              :value="item.sport"
            />
            </el-select>
          </el-col>
          <el-col :md="{span:8}" v-if='!homeTab' :xs="{span:24}" class="filter-item ">
            <!-- style="float: right;" -->

            <div style="float: right;">
      <a :href="exportLink" v-show="activeName === 'Course'"
   @click="()=>!list.length?$message('No export list'):''" >
            <button type="button" class="el-button el-button--success"><span>Export</span></button>
                   </a>
              <router-link v-show="activeName == 'Course'" :to="{path:`/trainSchedule/add`,params:{'actionToken':actionToken},query:{page:activeName,page:activeName}}">
                <button type="button" class="el-button el-button--success"><span>Add</span></button>
              </router-link>
            </div>

            <div v-show="activeName == 'TimeTable'" class="fr">
              <el-button class="selparent">
               <div>
                   <!-- {{listQuery.typeId+''+Number(i)===able}} -->
                  <el-select
                     v-model="listQuery.sport"
                    :placeholder="sortName[0].label"
                    class="filter-item"
                    clearable
                    @change="(l)=>sort_method(0,l)"
                  >
                  <el-option

                    v-for="item in sportList"
                   :key="item.sport"
                   :label="item.sportName"
                   :value="item.sport"
                  />

                  </el-select>
                </div>
              <!-- <div>
                     <el-select
                       v-model="listQuery.courseName"
                       :placeholder="sortName[1].label"
                       class="filter-item"
					            clearable
                       @change="(l)=>sort_method(1,l)"
                     >
                     <el-option
                         v-for="(ite,s,ks) in courseList"
                       :key="ks"
                       :label="ite"
                       :value="ite"
                     />
                     </el-select>
                   </div>
                    <div>
                          <el-select
                            clearable
                            v-model="listQuery.courseDetail"
                            :placeholder="sortName[2].label"
                            class="filter-item"
                            @change="(l)=>sort_method(2,l)"
                          >
                          <el-option
                              v-for="(ite,s,ks) in courseDetailList"
                            :key="ks"
                            :label="ite"
                            :value="ite"
                          />
                          </el-select>
                        </div> -->
              </el-button>

                    <el-button type="text" style="vertical-align: bottom;margin-bottom: 0;">
                      <!-- <div>
                        <el-button type="success"  @click="handleFilter" >
                          Filter
                        </el-button>
                      </div> -->

                      <a :href="exportLink"
                         @click="()=>!list.length?$message('No export list'):''" >
                                  <button type="button" class="el-button el-button--success"><span>Export</span></button>
                       </a>
                 </el-button>



            </div>
          </el-col>
        </el-row>
      </div>

      <el-table
        v-show="activeName !== 'Course'"
        ref="table"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        stripe
        @selection-change="handleSelectionChange"
        @sort-change="sort_change"
      >
        <el-table-column label="Sport" min-width="50"  prop="sportName" sortable="custom">
          <template slot-scope="scope" >
            {{ scope.row.sportName  }} {{ scope.row|clearInit($set)}}
          </template>
        </el-table-column>
        <el-table-column label="Course" min-width="80" prop="courseName" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.courseName }}
          </template>
        </el-table-column>
        <el-table-column label="Details" min-width="80" prop="detailsName" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.detailsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column :label="'Start'" width="120" align="center" prop="startTime" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.startTime }}
          </template>
        </el-table-column>
        <el-table-column :label="'End'"  align="center" prop="endTime" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.endTime  }}
          </template>
        </el-table-column>

        <el-table-column min-width="100" label="Coach/Helper" prop="coachCheckNum" sortable="custom">
          <template slot-scope="scope">
            {{  scope.row.coachNum || '0'}}
          </template>
        </el-table-column>

        <el-table-column label="Athlete" prop="athleteCheckNum" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.athleteNum || '0'}}
          </template>
        </el-table-column>

        <el-table-column label="Location" min-width="100" prop="locationName" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.locationName }}
          </template>
        </el-table-column>
        <el-table-column label="Status" prop="status" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.status }}
          </template>
        </el-table-column>

      </el-table>
      <el-table
        v-if="activeName==='Course'"
        ref="table"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        stripe
        @select="selectFn"
        @select-all="selectAllFn"
        @selection-change="handleSelectionChange"
        @sort-change="sort_change"
      >
        <el-table-column
          type="selection"
          fixed="left"
          width="40"
        />

        <el-table-column label="ID" width="120"  >
          <template slot-scope="scope">
             <router-link tag="a" :to="`/trainSchedule/add?page=${activeName}&id=${scope.row.id}`">
              {{ (scope.$index +1)+((listQuery.page-1)*listQuery.size) }}
            </router-link>
          </template>
        </el-table-column>

        <el-table-column label="Sport" prop="sportName" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.sportName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="Course" prop="courseName" sortable="custom">
          <template slot-scope="scope">
             <router-link tag="a" :to="`/trainSchedule/add?page=${activeName}&id=${scope.row.id}`">
            {{ scope.row.courseName }}
             </router-link>
          </template>
        </el-table-column>
        <el-table-column label="Details" min-width="150" prop="detailsName" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.detailsName || '-' }}
          </template>
        </el-table-column>

        <el-table-column :label="'Start Date'" min-width="110" align="center" prop="startDate" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.startDate | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column :label="'End Data'" min-width="110" align="center" prop="endDate" sortable="custom">
          <template slot-scope="scope">
            {{ scope.row.endDate | dateFormat }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="" width="60">
          <template slot-scope="scope">
            <div style="text-align: center;">
              <router-link tag="a" :to="`/trainSchedule/add?page=${activeName}&id=${scope.row.id}`">
                <el-button type="text" size="small">
                  <img src="../../assets/images/look.svg" class="btn-icon">
                </el-button>
              </router-link>

            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="sizes, prev, pager, next"
        :page-size="listQuery.size"
        :current-page="listQuery.page"
        :total="listQuery.total"
        class="pagination-container"
        :page-sizes="[25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  </div>
</template>
<script>
    import store from '@/store'
    // import { getSchedulesList } from '@/api/home'
    import { getTrainList ,getTypeCodeList  } from '@/api/trainSchedule'

    export default {
        filters: {
            statusFilter(status) {
                const statusMap = {
                    published: 'success',
                    draft: 'gray',
                    deleted: 'danger'
                }
                return statusMap[status]
            }
        },
        props:['homeTab'],
        data() {
            return {
                name:'',
                able:'',
               pickerVal: '',

               sortName: [{
                  belonging: 'MISCELLANEOUS',
                  typeCode: 'SPORTS_TYPE',
                  typeName: 'Sport',
                  label: 'sport',
                  value: '',
                   list: []
                 },
                {
                   typeCode: 'COURSE_TYPE',
                   typeName: 'Course Name',
                   belonging: 'TRAINING',
                   label: 'course',
                   value: ''
                 },
                 {
                   typeCode: 'COURSE_DETALL',
                   typeName: 'Course Detalls',
                   belonging: 'TRAINING',
                   label: 'courseDetails',
                   value: ''
                 }],
              pickerOptions: {
                      },
                      value1: '',
                      value2: '',

                sportMedicineList: {
                },
                actionToken: '',
                list: [],
                sportList:[],
                courseList:[],
                courseDetailList:[],
                listQuery: {
                    keyword: '',
                    page: 1,
                    exportToken:'',
                    //limit: 25,
                    total: 0,
                    courseName:'',
                    courseDetail:'',
                    //type: '',
                    sorting: 0,
                    uppderDate: '',
                    column: '',
                    size: 25,
                    courseIds:'',
                    sport:''
                },
                uppderDate: this.getToDay(),
                sportScienceList: {
                    list: [],
                    listQuery: {
                        page: 1,
                        limit: 25
                    }
                },
                listLoading: true,
                activeName: 'TimeTable',
                link: '/trainSchedule/add?page=Course',
                summaryList: [],
                listIndexs: [],
                minWindths: [],
                userType: store.getters.userType,
                courseAdmin:["HEAD_COACH" ,"ADMIN" ,"SUPER_ADMIN"].indexOf(store.getters.userType)>-1
            }
        },
        watch: {
            homeTab(h){
                if(h){
                  this.avtiveName='TimeTable'
                  this.fetchData({url:''})
                }
            },
            activeName(val) {
                this.$router.push(`${this.$route.path}?tab=${val}`)
                if (val === 'Course') this.listQuery.keyword=''
            },
            uppderDate(val) {
              this.trainScheduleList(this.listQuery.page, this.activeName)
               this.$refs.inputRef.pickerVisible = true
            }
        },
        mounted(e) {
          this.$refs.inputRef.pickerVisible = true
        },
        computed:{
          exportLink(){
            var Course = this.activeName==='Course'?'course':'lesson'
            if(this.listQuery.courseIds.length){
              this.listQuery.courseIds = this.listQuery.courseIds.map(lists=>lists.id)
              console.log('sd se', this.listQuery.courseIds)
            }

            var params='?token='+ encodeURIComponent(this.listQuery.exportToken)+'&sport='+this.listQuery.sport
           this.activeName!=='Course'? params +='&uppderDate='+this.uppderDate+'&courseDetail='+this.listQuery.courseDetail+'&courseName='+this.listQuery.courseName:'&keywork='+this.listQuery.keyword+(this.listQuery.courseIds?'&courseIds='+JSON.stringify(this.listQuery.courseIds):'')
            let url
            if(!this.list.length){
              url = 'javascript:void(0)'
              // this.$message('No export list')
            }else{
              url = process.env.VUE_APP_BASE_API + '/export/'+Course+'/xls'+params
            }
            return url
          }
        },
        created() {
            const query = this.$route.query
            if (query.tab) {
                this.activeName = query.tab || 'TimeTable'
            }
            this.fetchData()
        },
        methods: {

            fetchData() {
                const tabName = this.activeName
                this.listQuery.page = 1
                this.listQuery.total = 0
                //this.listQuery.column = 'id'
                 var sortName = this.sortName
                 if(!this.homeTab){
                  // var paramCode = { code: sortName[0].typeCode + ',' + sortName[1].typeCode + ',' + sortName[2].typeCode + ',' + 'VENUE' }
                   // getTypeCodeList(paramCode).then((res) => {
                   //   sortName[0].list = res.result
                   // })
                 }
                if (this.$refs.table) this.$refs.table.clearSort()
                this.trainScheduleList(this.listQuery.page, tabName)
            },
            trainScheduleList(page, tabName) {
                var that = this
                var url =this.homeTab?"home/lesson/list":'/course/obtain/lesson_list'// '/medical/sport_medical/page_list' //
                const params = {
                    page: page,
                    size: this.listQuery.size,
                    type: this.listQuery.type,
                    sorting: this.listQuery.sorting,
                    column: this.listQuery.column,
                    sport:this.listQuery.sport,

                }
                if (tabName === 'Course') {
                   params.keywork=this.listQuery.keyword //keyword 禪道4108 API:  参数变动 修改： keywork -- > keyword    添加 sport 运动id


                   url = '/course/obtain/course_list'// '/training/course/page_list'
                } else {
                    params.uppderDate = that.uppderDate
                    params.courseDetail= this.listQuery.courseDetail
                    params.courseList= this.listQuery.courseList
                }
                this.listLoading = true
                if (page === 1) {
                    this.list = []
                }
                getTrainList(url, params).then(response => {
                    if (response.status === 0) {
                        const data = response.result
                        this.listQuery.total = data.total ? data.total : this.listQuery.total
                        for (var i in data.list) {
                          data.list[i].idPrefix = this.$caseIdFormat(tabName, data.list[i].id)
                        }
                        this.sportList = data.sportList
                        this.sortName[0].list = data.sportList
                        this.list = data.list
                        this.listQuery.exportToken=data.exportToken
                        this.listQuery.page = page
                    }
                    that.listLoading = false
                })
            },
             sort_method(sm,list) {
                //this.listQuery.type = Number(sm) + 1
                // 只篩選 一條
                //this.listQuery.typeId = this.sortName[sm].value
                if(sm===0){
                   // this.listQuery.sport = list.sport
                    //this.courseList = list.courseList
                   // this.courseDetailList= list.courseDetailList

                }else{
                    //this.listQuery[sm==1?'courseName':'courseDetail '] = list
                }
                console.log("sn",sm,this)
                this.trainScheduleList(1, this.activeName)
            },

            sort_change(column) {
                this.listQuery.page = 1

                if (column.prop && column.order) {
                    this.listQuery.sorting = column.order === 'ascending' ? 0 : 1
                    this.listQuery.column = column.prop
                    this.trainScheduleList(1, this.activeName)
                }
                //this.showed_data = this.filtered_data.slice(0, this.page_size) // show only one page
            },
            minWidth(i, text) {
                let w = 100
                if (text.length >= 10) {
                     w = 130
                } else if (text.length < 5 && text !== '') {
                     w = 50
                } else {
                     w = 100
                }
                // const w = text.length >= 10 ? 130 : 100
                console.log(text, text.length)
                return w
            },
            // pageSize变化事件
            handleSizeChange(val) {
              this.listQuery.limit = val
              this.fetchData()
            },
            // pageNum变化事件
            handleCurrentChange(page) {
                this.trainScheduleList(page, this.activeName)
            },
            sportMedicineFormatLink(row, column) {
                return row.row.id = 1
            },
            forthSet(dateStr, pattern = '') {
                // 根据给定的时间字符串，得到特定的时间
                var dt = new Date(dateStr)
                //   yyyy-mm-dd
                var y = dt.getFullYear()
                var m = (dt.getMonth() + 1).toString().padStart(2, '0')
                var d = dt.getDate().toString().padStart(2, '0')
                if (pattern.toLowerCase() === 'yyyy-mm-dd') {
                    return `${y}-${m}-${d}`
                } else {
                    var hh = dt.getHours().toString().padStart(2, '0')
                    var mm = dt.getMinutes().toString().padStart(2, '0')
                    var ss = dt.getSeconds().toString().padStart(2, '0')
                    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
                }
            },
            handleClick(tab, event) {

                if(tab.name!==this.$route.query.tab){
                   this.listLoading = true
                  this.listQuery.sport = ''

                  this.listQuery.keyword = ''
                  this.fetchData()

                }

            },
            handleFilter() {
                this.fetchData()
            },

        toggleSelection(rows) {
        if (rows) {
            rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
        })
        } else {
            this.$refs.multipleTable.clearSelection()
        }
        },
        selectAllFn(val){
          this.listQuery.courseIds = val
        },
        selectFn(val,or){
          this.listQuery.courseIds = val
          console.log('sd',val,or)
        },
        handleSelectionChange(val) {
          this.multipleSelection = val
        }
        }
    }
</script>
<style lang="scss">
#Training{
div.el-date-editor{
    >input,>span{
      display:none !important;

    }
    .el-popper.fix-popper{
    display:inline-block !important;
    position:initial !important;
    opacity:1 !important;
    margin-top: -20px;
    transform:none !important;
    .el-picker-panel__content,.el-date-picker__header{
      margin:10px;
      }
    .el-date-table {
      th{
      text-align:center;
      }
      td, td div, td span{
      height:1.4rem;line-height: 1.4rem;padding:0;
     }
    }

    }
}
}
</style>
<style lang='scss' scoped >

    .selparent .el-select .el-input__inner{
      width: 250px;
    }
</style>
